package space.panker916.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static space.panker916.utils.Constants.*;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    // 忽略掉对静态资源的拦截
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/resources/**");
    }

    // 进行授权，对权限的约束和处理
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        // 授权
        http.authorizeRequests()
                .antMatchers(
                        "/user/setting", "user/upload", "user/updatePassword",
                        "/letter/**", "/notice/**",
                        "/like", "/follow", "/unFollow",
                        "/discuss/add/", "/comment/add/**"
                ).hasAnyAuthority(AUTHORITY_USER, AUTHORITY_ADMIN, AUTHORITY_MODERATOR)
                .antMatchers(
                        "/discuss/top", "/discuss/wonderful"
                ).hasAnyAuthority(AUTHORITY_ADMIN, AUTHORITY_MODERATOR)
                .antMatchers(
                        "/discuss/delete", "/data/**"
                ).hasAnyAuthority(AUTHORITY_ADMIN)
                .anyRequest().permitAll().and().csrf().disable();

        // 授权不够时的处理
        http.exceptionHandling()
                .authenticationEntryPoint(new AuthenticationEntryPoint() {
                    // 没有登录时的处理
                    @Override
                    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
                        // 判断该请求是 同步请求 还是 异步请求（只要是根据请求头的 x-requested-with 值）

                        System.out.println("现在这里判断是否登录。。。");
                        SecurityContext context = SecurityContextHolder.getContext();
                        System.out.println("在过滤器中的：   context = " + context);

                        String xRequestedWith = request.getHeader("x-requested-with");
                        if ("XMLHttpRequest".equalsIgnoreCase(xRequestedWith)) {
                            // 异步请求
                            response.getWriter().write("login");
                        } else {
                            // 同步请求
                            response.sendRedirect(request.getContextPath() + "/login");
                        }
                    }
                })
                .accessDeniedHandler(new AccessDeniedHandler() {
                    // 权限不足时的处理
                    @Override
                    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
                        // 判断该请求是 同步请求 还是 异步请求（只要是根据请求头的 x-requested-with 值）
                        String xRequestedWith = request.getHeader("x-requested-with");
                        if ("XMLHttpRequest".equalsIgnoreCase(xRequestedWith)) {
                            // 异步请求
                            response.getWriter().write("denied");
                        } else {
                            // 同步请求
                            response.sendRedirect(request.getContextPath() + "/denied");
                        }
                    }
                });

        // Security 底层默认会拦截 /logout 请求，进行退出处理
        // 我们要覆盖它默认的逻辑，这样才能执行我们自己的退出代码（进行一个善意的欺骗）
        http.logout().logoutUrl("/securityLogout");

    }
}
